package cn.edu.jnu.supershopper;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import androidx.annotation.NonNull;

import java.util.ArrayList;
import java.util.Random;

import cn.edu.jnu.supershopper.Game.Background;
import cn.edu.jnu.supershopper.Game.Bullet;
import cn.edu.jnu.supershopper.Game.Enemy;
import cn.edu.jnu.supershopper.Game.Explosion;
import cn.edu.jnu.supershopper.Game.Myplane;

public class GameView extends SurfaceView implements SurfaceHolder.Callback, Runnable{
    public static final int TIME_IN_FRAME = 30;
    private SurfaceHolder mSurfaceHolder;
    //绘图的Canvas
    private Canvas canvas;
    private Paint paint;
    //子线程标志位
    public boolean isRun;
    private int count = 0;
    //手机屏幕宽高
    public static int mScreenWidth=0,mScreenHeight=0;
    //背景对象
    private Background back;
    //我的飞机
    private Myplane myplane;
    //子弹
    private Bullet bullet;
    private ArrayList<Bullet> bulletList = new ArrayList<Bullet>();
    //敌机
    private Enemy enemy;
    private ArrayList<Enemy> enemies = new ArrayList<Enemy>();
    private int[] enemiesPic = new int[]{R.drawable.enemy_1,R.drawable.enemy_2};
    //爆炸对象
    private Explosion explosion;

    public GameView(Context context) {
        super(context);
        mSurfaceHolder = getHolder();
        mSurfaceHolder.addCallback(this);
        canvas = new Canvas();
        paint = new Paint();
        paint.setColor(Color.WHITE);
        paint.setTextSize(50);

        back = new Background(context, R.drawable.backgroud2);
        myplane = new Myplane(context,R.drawable.me1);
        explosion = new Explosion(context, R.drawable.enemy_1over4);
    }

    @Override
    public void surfaceCreated(@NonNull SurfaceHolder holder) {
        //开始游戏循环线程
        isRun = true;
        //获取屏幕宽高
        mScreenWidth = this.getWidth();
        mScreenHeight = this.getHeight();
        initGame();
        new Thread(this).start();
    }

    private void initGame() {
        back.fitScreen(mScreenWidth,mScreenHeight);
        // 玩家飞船出生点
        myplane.posX = mScreenWidth / 2 - myplane.width;
        myplane.posY = mScreenHeight / 4 * 3;
    }

    @Override
    public void run() {
        while (isRun){
            long startTime = System.currentTimeMillis();
            //加上线程安全锁
            synchronized (mSurfaceHolder){
                //拿到当前画布锁定
                canvas = mSurfaceHolder.lockCanvas();
                if (!myplane.isDied){
                    drawGameUI();
                    logic();
                }else{
                    //画背景
                    canvas.drawBitmap(back.bitmap,0,0,paint);
                    paint.setTextAlign(Paint.Align.CENTER);
                    canvas.drawText("游戏结束，点击屏幕结算",mScreenWidth/2,mScreenHeight/2,paint);
                }
                mSurfaceHolder.unlockCanvasAndPost(canvas);
            }
            long endTime = System.currentTimeMillis();
            int diffTime = (int)(endTime - startTime);
            while (diffTime <= TIME_IN_FRAME){
                diffTime = (int)(System.currentTimeMillis() - startTime);
                //线程等待
                Thread.yield();
            }
        }
    }

    private void logic() {
        count++;
        if(count >= Integer.MAX_VALUE) count = 0;
        //back.move(); //背景运动
        if(back.posY>=mScreenHeight) back.posY = -mScreenHeight;

        //每隔一段时间随机生成敌机
        if(count%50 == 0){
            enemy = new Enemy(getContext(),enemiesPic[new Random().nextInt(enemiesPic.length)]);
            enemy.posX = new Random().nextInt(mScreenWidth - enemy.width);
            enemies.add(enemy);
        }
        //敌机移动
        for(int i =0; i<enemies.size();i++){
            enemies.get(i).move();
            //出界移除
            if(enemies.get(i).posY>mScreenHeight) enemies.remove(i);
            //触碰检查
            if(i<enemies.size()&& enemies.get(i).touchCheck(myplane)){
                if(myplane.life>1){
                    myplane.life--;
                    explosion.setExplosionP(enemies.get(i));
                    enemies.remove(i);
                }else myplane.isDied = true;
            }
        }
        //玩家飞船开火，生成子弹
        if(myplane.isFire && count %5 == 0){
            myplane.isFire = false;
            bullet = new Bullet(getContext(),R.drawable.bullet_1);
            //子弹坐标为当前飞机的坐标
            bullet.posX = myplane.posX + myplane.width/2 - bullet.width/2;
            bullet.posY = myplane.posY;
            bulletList.add(bullet);
        }
        for(int i =0; i<bulletList.size();i++){
            bulletList.get(i).move();//子弹移动
            //出界移除
            if(bulletList.get(i).posY<0) bulletList.remove(i);

            //遍历敌机，判断是否打中
            for(int j=0;j<enemies.size();j++){
                if(j<enemies.size() && i<bulletList.size()
                        && enemies.get(j).touchCheck(bulletList.get(i))){
                    myplane.score +=100;
                    explosion.setExplosionP(enemies.get(j));
                    enemies.remove(j);
                    bulletList.remove(i);
                }
            }
        }
        //爆炸动画
        if(explosion.isStart && count%3 ==0){
            explosion.startExplosion();
        }
    }

    private void drawGameUI() {
        back.draw(canvas,paint);
        explosion.draw(canvas,paint);
        for(int i = 0;i<enemies.size();i++){
            enemies.get(i).draw(canvas,paint);
        }
        myplane.draw(canvas,paint);
        for (int i = 0; i < bulletList.size(); i++) {
            bulletList.get(i).draw(canvas, paint);
        }
        paint.setTextAlign(Paint.Align.LEFT);
        canvas.drawText("得分：" + myplane.score, 0, 50, paint);
        canvas.drawText("生命：" + myplane.life, 0, 100, paint);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        myplane.touchEvent(event);
        if(myplane.isDied){
            isRun = false;
            //跳转结算界面
            Intent intent = new Intent(this.getContext(), GameOverActivity.class);
            String score = Integer.toString(myplane.score);
            intent.putExtra("score", score);
            this.getContext().startActivity(intent);
        }else{
            myplane.isFire = true; //点击屏幕开火
        }
        return super.onTouchEvent(event);
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {

    }

}
